
#! /usr/bin/python

import sys
import os
import time
import copy
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../..')
from spade import *
class OMS(Agent.Agent):
    def _setup(self):
        print "setup"
        virtual=OrganizationalUnit.OrganizationalUnit(self,"virtual","","","")
        self.units=[virtual]

    def registerUnit(self,unitID,type,goalList,parent):
        """
        Registers a new unit in the platform
        """
        if parent=="":parent="virtual"
        parent=parent.lower()
        unitID=unitID.lower()
        type=type.lower()
        #chek type
        types=["flat","team","hierarchy","bureaucracy","matrix","federation","coalition","congregation"]
        if type not in types:
            print "Send Invalid Status (not valid type)"
            return
        #check if the parents exists
        exists=False
        duplicate=False
        for u in self.units:
            if u.getUnitID()==parent:
                exists=True
            if u.getUnitID()==unitID:
                duplicate=True
        #checkTypes
        if not exists:
            print "Send Invalid Status (parent not exists)"
            return
        if duplicate:
            print "Send Duplicate Status"
            return
        organization=OrganizationalUnit.OrganizationalUnit(self,unitID,type,parent,goalList)
        print unitID,type,goalList,parent
        print organization.getInfo()
        result=organization.registerUnit()
        if result!=True:
            print "Send Generic Error"
            return
        self.units.append(organization)
        for u in self.units:
            if u.getUnitID()==parent:
                u.appendUnit(unitID)

    def deregisterUnit(self,unitID):
        unitID=unitID.lower()
        for u in self.units:
            if u.getUnitID()==unitID:
                print u.getRoleList(),u.getUnitList(),u.getUnitID(),unitID
                if u.getRoleList()==[] and u.getUnitList()==[]:
                    u.deregisterUnit()
                    self.units.remove(u)
                    return
                else:
                     print "Send Invalid (has Role or Units)",unitID
                     return
        print "Send Invalid (not valid unitID)",unitID
        return


    def _process(self):
	 pass



if __name__ == "__main__":
    agent = "oms@apolo.dsic.upv.es"

    b = OMS(agent,"pasword")
    b.start()
    b._setup()
    print "Agent "+agent+" registering"
    units=[]
    unitID="Unit"
    Type="Congregation"
    Goal="Travel Reserve"
    Parent="Virtual"
    b.registerUnit(unitID,Type,Goal,Parent)
    for u in b.units:
        print u.getInfo()
    b.deregisterUnit("Virtual")
    b.deregisterUnit(unitID)
    b.deregisterUnit("Jaja")
    b.units
    b._shutdown()



